package fr.umlv.ig.listenerFactory;

import java.awt.Component;
import java.awt.event.MouseAdapter;

import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeCellRenderer;

import fr.umlv.ig.adapter.TrainTreeModel;
import fr.umlv.ig.metroFactory.GraphicFactory;
import fr.umlv.ig.model.Line;
import fr.umlv.ig.model.Train;


/**
 * Class with static methods which contains listener for a {@link JTree} with a
 * {@link TrainTreeModel}.
 * 
 * @author jenseric
 * @author wiliam
 *
 */
public class TrainTreeListenerFactory {


	/**
	 * Returns a {@link TreeSelectionListener} for a {@link JTree}
	 * @param jtree the {@link JTree} which listen with the listener returned.
	 * @return a {@link TreeSelectionListener} for a {@link JTree} with a 
	 * {@link TrainTreeModel}.
	 */
	public static TreeSelectionListener getSelectionListener(final JTree jtree) {

		final TrainTreeModel treeModel = (TrainTreeModel) jtree.getModel();		
		return new TreeSelectionListener() {
			@Override
			public void valueChanged(TreeSelectionEvent e) {
				if(jtree.getLastSelectedPathComponent() != null){
					Object o = jtree.getLastSelectedPathComponent();
					if(o instanceof Line || o instanceof Train) {
		
						treeModel.selected(o);
					}
					
				}
			}
		};		
	
	}

	/**
	 * {@link MouseAdapter} for a {@link JTree} which has a {@link TrainTreeModel}.
	 * @param jtree the JTree which will have the {@link MouseAdapter}
	 * @return {@link MouseAdapter} for a {@link JTree} which has a 
	 *          {@link TrainTreeModel}.
	 */
	@SuppressWarnings("serial")
	public static TreeCellRenderer getTreeCellRenderer(TrainTreeModel treeModel) {
		return new DefaultTreeCellRenderer() {
			@Override
			public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
				if (value instanceof Line) {
					Line l = (Line)value;
					value="Line" + l.getNumber();
					setClosedIcon(GraphicFactory.ICONLINE);
					setOpenIcon(GraphicFactory.ICONLINE);

				}

				if (value instanceof Train) {
					Train train = (Train)value;
					value= "Train "+train.getId();
					setClosedIcon(GraphicFactory.ICONTRAIN);
					setOpenIcon(GraphicFactory.ICONTRAIN);
				}

				return super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
			}
		};
	}

	
}
